package com.scorpio.appuser.service.impl;

import com.scorpio.appuser.dto.AppUserDetailsDTO;
import com.scorpio.appuser.service.AppUserService;
import com.scorpio.appuser.domain.AppUserEntity;
import com.scorpio.appuser.mapper.AppUserMapper;
import com.scorpio.common.service.impl.BaseServiceImpl;
import com.scorpio.common.utils.ConvertUtils;
import com.scorpio.order.enums.OrderStatusEmun;
import com.scorpio.order.service.OrderService;
import com.scorpio.redis.RedisCache;
import com.scorpio.redis.constant.AppCacheConstant;
import com.scorpio.redis.constant.AppConfigConstant;
import com.scorpio.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AppUserServiceImpl extends BaseServiceImpl<AppUserMapper, AppUserEntity> implements AppUserService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private OrderService orderService;

    @Override
    public AppUserEntity findCacheUser(Long id) {
        String key = AppCacheConstant.CACHE_LOGIN_USER + id;
        AppUserEntity user = redisCache.getCacheObject(key);
        if (user == null) {
            user = selectById(id);
            if (user != null) {
                redisCache.setCacheObject(key, user, 60, TimeUnit.SECONDS);
            }
        }
        return user;
    }

    @Override
    public AppUserDetailsDTO details(Long id) {
        AppUserDetailsDTO dto = ConvertUtils.sourceToTarget(baseDao.selectById(id), AppUserDetailsDTO.class);
        dto.setServerWechat(sysConfigService.selectConfigByKey(AppConfigConstant.CONFIG_SERVER_WECHAT));
        dto.setCountOrderStatus0(orderService.countByStatus(id,OrderStatusEmun.Status0));
        dto.setCountOrderStatus2(orderService.countByStatus(id,OrderStatusEmun.Status2));
        dto.setCountOrderStatus3(orderService.countByStatus(id,OrderStatusEmun.Status3));
        return dto;
    }
}
